package com.example.teaching_server.controller;

import com.example.teaching_server.common.ApiResponse;
import com.example.teaching_server.dto.WeekDTO;
import com.example.teaching_server.exception.TermNotFoundException;
import com.example.teaching_server.service.WeekCalculationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/weeks")
@RequiredArgsConstructor
@Tag(name = "学期周次管理", description = "学期周次信息查询接口")
public class WeekController {
    private final WeekCalculationService weekService;

    /**
     * 获取学期周次列表
     */
    @GetMapping("/by-term")
    @Operation(summary = "获取学期周次列表", description = "根据学期ID获取周次数据列表")
    public ApiResponse<List<WeekDTO>> getTermWeeks(
            @Parameter(description = "学期ID") @RequestParam Long termId,
            @Parameter(description = "周起始日（1-7，1=周一，7=周日）") @RequestParam(defaultValue = "1") int startDay) {

        log.info("开始获取学期周次: termId={}, startDay={}", termId, startDay);

        try {
            List<WeekDTO> weeks = weekService.getTermWeeks(termId, startDay);
            log.info("成功获取学期{}的{}个周次", termId, weeks.size());
            return ApiResponse.success("周次数据获取成功", weeks);
        } catch (TermNotFoundException e) {
            log.warn("学期不存在: termId={}", termId);
            return ApiResponse.fail("指定的学期不存在");
        } catch (IllegalArgumentException e) {
            log.warn("参数错误: termId={}, startDay={}, error={}", termId, startDay, e.getMessage());
            return ApiResponse.fail("参数错误: " + e.getMessage());
        } catch (Exception e) {
            log.error("获取学期周次失败: termId={}", termId, e);
            return ApiResponse.fail("获取周次数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前学期的周次
     */
    @GetMapping("/current-term")
    @Operation(summary = "获取当前学期周次", description = "获取当前活跃学期的周次数据")
    public ApiResponse<List<WeekDTO>> getCurrentTermWeeks(
            @Parameter(description = "周起始日（1-7，1=周一，7=周日）") @RequestParam(defaultValue = "1") int startDay) {

        log.info("开始获取当前学期周次: startDay={}",startDay);

        try {
            // 这里需要实现获取当前学期ID的逻辑
            // 暂时返回空列表，需要根据实际情况实现
            List<WeekDTO> weeks = new ArrayList<>();
            log.info("成功获取当前学期{}个周次", weeks.size());
            return ApiResponse.success("当前学期周次数据获取成功", weeks);
        } catch (Exception e) {
            log.error("获取当前学期周次失败", e);
            return ApiResponse.fail("获取当前学期周次失败: " + e.getMessage());
        }
    }

    /**
     * 获取指定日期的周次信息
     */
    @GetMapping("/by-date")
    @Operation(summary = "获取日期对应周次", description = "根据指定日期获取对应的周次信息")
    public ApiResponse<WeekDTO> getWeekByDate(
            @Parameter(description = "查询日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
    @Parameter(description = "周起始日（1-7，1=周一，7=周日）") @RequestParam(defaultValue = "1") int startDay) {

        log.info("开始获取日期对应周次: date={}, startDay={}", date, startDay);

        try {
            // 这里需要实现根据日期获取周次信息的逻辑
            // 暂时返回空对象，需要根据实际情况实现
            WeekDTO week = new WeekDTO();
            log.info("成功获取日期{}的周次信息", date);
            return ApiResponse.success("周次信息获取成功", week);
        } catch (Exception e) {
            log.error("获取周次信息失败: date={}", date, e);
            return ApiResponse.fail("获取周次信息失败: " + e.getMessage());
        }
    }

    /**
     * 路径参数接口（兼容性保留）
     */
    @GetMapping("/term/{termId}")
    @Operation(summary = "获取学期周次(路径参数)", description = "使用路径参数获取学期周次数据")
    public ApiResponse<List<WeekDTO>> getTermWeeksWithPath(
            @Parameter(description = "学期ID") @PathVariable Long termId,
            @Parameter(description = "周起始日（1-7，1=周一，7=周日）") @RequestParam(defaultValue = "1") int startDay) {

        log.info("开始获取学期周次(路径参数): termId={}, startDay={}", termId, startDay);

        // 直接调用新的查询参数接口
        return getTermWeeks(termId, startDay);
    }
}
